angular.module("APP", [])

.config(function($provide, $httpProvider) {
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
	$httpProvider.defaults.withCredentials = true;
	/**
	 * ajax 拦截器。
	 */
	$provide.factory('httpInterceptor', function($q) {
		var baseUrl = "http://www.txiaoyuan.cn/index/t.php";
		return {
			request: function(cfig) {
				var url = cfig.url;
				cfig.cache = false;
				if(cfig.baseUrl) {
					if(url && url.substring(0, 1) == "/") {
						url = url.substring(1);
					}
					cfig.url = baseUrl + url;
				}

				return cfig;
			}
		};
	});
	$httpProvider.interceptors.push('httpInterceptor');
})

.controller("appController", ["$scope", "$http", "$filter", function($scope, $http, $filter) {
	var notification;
	var ids = [];
	
	function tip(){
		if(notification){
			notification.close();
		}
		/**
		 * 获取订单
		 */
		$http({
			url:"?m=Admin&c=ApiSchool&a=getOrderList",
			method:"post",
			baseUrl:true,
			params:{status:1,count:50,page:1}
		}).success(function(data){
			var orders = data.data;
			if(orders.length>0){
				var count = 0;
				for(var i=0;i<orders.length;i++){
					if(ids.indexOf(orders[i].order_id)<0){
						count+=1;
						ids.push(orders[i].order_id);
					}
				}
				
				chrome.browserAction.setBadgeText({text:orders.length.toString()});
				
				if(count>0){
					notification = new Notification("您有新的未处理订单", {
						icon: 'image/48.png',
						body: '您有'+count+"个新订单，快去处理吧"
					});
					notification.onclick = function(){
						chrome.windows.getLastFocused({populate:false, windowTypes:["normal"]}, function(win){
							if(!win){
								chrome.windows.create({url: "http://www.txiaoyuan.cn/ht_user/order.html"});
							} else {
								chrome.tabs.create({url: "http://www.txiaoyuan.cn/ht_user/order.html"});
							}
						});
						
						notification.close();
					}
				}
			} else {
				chrome.browserAction.setBadgeText({text:""});
			}
		});
	}
	
	/*半分钟检查一次新订单*/
	tip();
	setInterval(tip, 30000);
}]);